import { useState } from 'react';
import { useGameStore } from '@/store/game-store';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { ItemCard } from '@/components/item-card';
import { Item } from '@/types/game';
import { 
  Package, 
  Sword, 
  Shield, 
  Gem,
  User,
  TrendingUp,
  Coins
} from 'lucide-react';

export function InventoryPage() {
  const { 
    player, 
    inventory, 
    equipment, 
    equipItem, 
    unequipItem, 
    removeItem,
    gold 
  } = useGameStore();
  
  const [selectedTab, setSelectedTab] = useState('all');

  // 按类型筛选物品
  const filterItems = (type?: string) => {
    if (!type || type === 'all') return inventory;
    return inventory.filter(inv => inv.item.type === type);
  };

  // 使用消耗品
  const handleUseItem = (item: Item) => {
    if (item.type === 'consumable') {
      // 这里应该实现具体的使用效果
      console.log(`使用了 ${item.name}`);
      removeItem(item.id, 1);
    }
  };

  // 装备物品
  const handleEquipItem = (item: Item) => {
    equipItem(item);
    removeItem(item.id, 1);
  };

  // 卸下装备
  const handleUnequipItem = (slot: 'weapon' | 'armor' | 'accessory') => {
    const item = equipment[slot];
    if (item) {
      unequipItem(slot);
      // 将装备放回背包
      // addItem(item, 1); // 这里需要在store中实现
    }
  };

  // 计算装备属性加成
  const getEquipmentStats = () => {
    const stats = { attack: 0, defense: 0, health: 0, mana: 0, speed: 0 };
    
    Object.values(equipment).forEach(item => {
      if (item?.stats) {
        Object.entries(item.stats).forEach(([stat, value]) => {
          if (stat in stats) {
            stats[stat as keyof typeof stats] += value || 0;
          }
        });
      }
    });
    
    return stats;
  };

  const equipmentStats = getEquipmentStats();
  const totalValue = inventory.reduce((sum, inv) => sum + (inv.item.price * inv.quantity), 0);

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <div className="text-center space-y-2">
        <h1 className="text-3xl font-bold bg-gradient-to-r from-blue-400 to-blue-600 bg-clip-text text-transparent">
          背包系统
        </h1>
        <p className="text-slate-400">
          管理物品和装备，提升角色实力
        </p>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* 左侧：装备栏 */}
        <div className="lg:col-span-1 space-y-4">
          {/* 当前装备 */}
          <Card className="bg-slate-800/50 border-slate-700">
            <CardHeader>
              <CardTitle className="text-blue-400 flex items-center space-x-2">
                <User className="h-5 w-5" />
                <span>当前装备</span>
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              {/* 武器槽 */}
              <div className="space-y-2">
                <div className="flex items-center justify-between">
                  <span className="text-sm text-slate-400 flex items-center space-x-1">
                    <Sword className="h-4 w-4" />
                    <span>武器</span>
                  </span>
                  {equipment.weapon && (
                    <Button
                      onClick={() => handleUnequipItem('weapon')}
                      size="sm"
                      variant="outline"
                      className="text-xs"
                    >
                      卸下
                    </Button>
                  )}
                </div>
                {equipment.weapon ? (
                  <ItemCard 
                    item={equipment.weapon} 
                    showActions={false}
                    className="w-full"
                  />
                ) : (
                  <div className="h-24 border-2 border-dashed border-slate-600 rounded-lg flex items-center justify-center text-slate-500 text-sm">
                    未装备武器
                  </div>
                )}
              </div>

              {/* 护甲槽 */}
              <div className="space-y-2">
                <div className="flex items-center justify-between">
                  <span className="text-sm text-slate-400 flex items-center space-x-1">
                    <Shield className="h-4 w-4" />
                    <span>护甲</span>
                  </span>
                  {equipment.armor && (
                    <Button
                      onClick={() => handleUnequipItem('armor')}
                      size="sm"
                      variant="outline"
                      className="text-xs"
                    >
                      卸下
                    </Button>
                  )}
                </div>
                {equipment.armor ? (
                  <ItemCard 
                    item={equipment.armor} 
                    showActions={false}
                    className="w-full"
                  />
                ) : (
                  <div className="h-24 border-2 border-dashed border-slate-600 rounded-lg flex items-center justify-center text-slate-500 text-sm">
                    未装备护甲
                  </div>
                )}
              </div>

              {/* 饰品槽 */}
              <div className="space-y-2">
                <div className="flex items-center justify-between">
                  <span className="text-sm text-slate-400 flex items-center space-x-1">
                    <Gem className="h-4 w-4" />
                    <span>饰品</span>
                  </span>
                  {equipment.accessory && (
                    <Button
                      onClick={() => handleUnequipItem('accessory')}
                      size="sm"
                      variant="outline"
                      className="text-xs"
                    >
                      卸下
                    </Button>
                  )}
                </div>
                {equipment.accessory ? (
                  <ItemCard 
                    item={equipment.accessory} 
                    showActions={false}
                    className="w-full"
                  />
                ) : (
                  <div className="h-24 border-2 border-dashed border-slate-600 rounded-lg flex items-center justify-center text-slate-500 text-sm">
                    未装备饰品
                  </div>
                )}
              </div>
            </CardContent>
          </Card>

          {/* 装备属性加成 */}
          <Card className="bg-slate-800/50 border-slate-700">
            <CardHeader>
              <CardTitle className="text-green-400 flex items-center space-x-2">
                <TrendingUp className="h-5 w-5" />
                <span>装备加成</span>
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-2">
                {Object.entries(equipmentStats).map(([stat, value]) => (
                  <div key={stat} className="flex justify-between text-sm">
                    <span className="text-slate-400">
                      {stat === 'attack' ? '攻击力' :
                       stat === 'defense' ? '防御力' :
                       stat === 'health' ? '生命值' :
                       stat === 'mana' ? '灵力值' :
                       stat === 'speed' ? '速度' : stat}:
                    </span>
                    <span className={value > 0 ? 'text-green-400' : 'text-slate-500'}>
                      +{value}
                    </span>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        </div>

        {/* 右侧：背包物品 */}
        <div className="lg:col-span-2">
          <Card className="bg-slate-800/50 border-slate-700">
            <CardHeader>
              <div className="flex items-center justify-between">
                <div>
                  <CardTitle className="text-blue-400 flex items-center space-x-2">
                    <Package className="h-5 w-5" />
                    <span>背包物品</span>
                  </CardTitle>
                  <CardDescription className="text-slate-400 mt-1">
                    {inventory.length} 种物品 • 总价值 {totalValue} 金币
                  </CardDescription>
                </div>
                <div className="flex items-center space-x-2 text-amber-400">
                  <Coins className="h-5 w-5" />
                  <span className="font-bold">{gold.toLocaleString()}</span>
                </div>
              </div>
            </CardHeader>
            <CardContent>
              <Tabs value={selectedTab} onValueChange={setSelectedTab}>
                <TabsList className="grid w-full grid-cols-5 bg-slate-700 mb-4">
                  <TabsTrigger value="all">全部</TabsTrigger>
                  <TabsTrigger value="weapon">武器</TabsTrigger>
                  <TabsTrigger value="armor">护甲</TabsTrigger>
                  <TabsTrigger value="consumable">消耗品</TabsTrigger>
                  <TabsTrigger value="material">材料</TabsTrigger>
                </TabsList>

                <TabsContent value="all" className="mt-4">
                  <div className="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-4">
                    {inventory.map((inv, index) => (
                      <ItemCard
                        key={`${inv.item.id}-${index}`}
                        item={inv.item}
                        quantity={inv.quantity}
                        onUse={handleUseItem}
                        onEquip={handleEquipItem}
                      />
                    ))}
                  </div>
                </TabsContent>

                <TabsContent value="weapon" className="mt-4">
                  <div className="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-4">
                    {filterItems('weapon').map((inv, index) => (
                      <ItemCard
                        key={`${inv.item.id}-${index}`}
                        item={inv.item}
                        quantity={inv.quantity}
                        onEquip={handleEquipItem}
                      />
                    ))}
                  </div>
                </TabsContent>

                <TabsContent value="armor" className="mt-4">
                  <div className="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-4">
                    {filterItems('armor').map((inv, index) => (
                      <ItemCard
                        key={`${inv.item.id}-${index}`}
                        item={inv.item}
                        quantity={inv.quantity}
                        onEquip={handleEquipItem}
                      />
                    ))}
                  </div>
                </TabsContent>

                <TabsContent value="consumable" className="mt-4">
                  <div className="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-4">
                    {filterItems('consumable').map((inv, index) => (
                      <ItemCard
                        key={`${inv.item.id}-${index}`}
                        item={inv.item}
                        quantity={inv.quantity}
                        onUse={handleUseItem}
                      />
                    ))}
                  </div>
                </TabsContent>

                <TabsContent value="material" className="mt-4">
                  <div className="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-4">
                    {filterItems('material').map((inv, index) => (
                      <ItemCard
                        key={`${inv.item.id}-${index}`}
                        item={inv.item}
                        quantity={inv.quantity}
                      />
                    ))}
                  </div>
                </TabsContent>
              </Tabs>

              {inventory.length === 0 && (
                <div className="text-center py-12 text-slate-400">
                  <Package className="h-16 w-16 mx-auto mb-4 opacity-50" />
                  <h3 className="text-lg font-semibold mb-2">背包空空如也</h3>
                  <p className="text-sm">
                    通过修炼、战斗和完成任务获得物品
                  </p>
                </div>
              )}
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}